//
//  MYKSCrashFilter.m
//  MySDK
//
//  Created by shuai on 2025/11/1.
//

#import "MYKSCrashFilter.h"
#import "KSCrashReport.h"
#import "AnyThinkCrashFilter.h"
#import <mach-o/dyld.h>

@interface MYKSCrashFilter()
/// SDK 标识符
@property (nonatomic, copy) NSString *libraryIdentifier;
@end

@implementation MYKSCrashFilter

- (instancetype)init {
    return [self initWithSDKIdentifier:@"MySDK"];
}

- (instancetype)initWithSDKIdentifier:(NSString *)libraryIdentifier {
    if (self = [super init]) {
        _libraryIdentifier = [libraryIdentifier copy];
        
        // 初始化地址范围筛选器
        [[AnyThinkCrashFilter sharedInstance] setupWithSDKIdentifier:libraryIdentifier];
    }
    return self;
}

- (void)filterReports:(NSArray<id<KSCrashReport>> *)reports
         onCompletion:(nullable KSCrashReportFilterCompletion)onCompletion {
    if (!reports || reports.count == 0) {
        // 无报告时直接回调
        kscrash_callCompletion(onCompletion, @[], nil);
        return;
    }

    // 使用地址范围筛选器筛选崩溃报告
    NSMutableArray<id<KSCrashReport>> *filteredReports = [NSMutableArray array];
    AnyThinkCrashFilter *addressFilter = [AnyThinkCrashFilter sharedInstance];
    
    // 检查地址范围是否已初始化，如果未初始化则尝试重新初始化
    if (!addressFilter.isAddressRangeValid) {
        NSLog(@"[MYKSCrashFilter] 警告：地址范围未初始化，尝试重新初始化（标识符：%@）", self.libraryIdentifier);
        [addressFilter setupWithSDKIdentifier:self.libraryIdentifier];
        
        // 重新检查初始化结果
        if (!addressFilter.isAddressRangeValid) {
            NSLog(@"[MYKSCrashFilter] ❌ 错误：无法初始化地址范围，可能是 SDK 标识符 '%@' 不匹配。将打印所有已加载的镜像供参考：", self.libraryIdentifier);
            
            // 打印所有已加载的镜像，帮助调试
            const uint32_t imageCount = _dyld_image_count();
            for (uint32_t i = 0; i < imageCount; i++) {
                const char *imagePathC = _dyld_get_image_name(i);
                if (imagePathC != NULL) {
                    NSString *imagePath = [NSString stringWithUTF8String:imagePathC];
                    NSLog(@"[MYKSCrashFilter] 已加载镜像 %u: %@", i, imagePath);
                }
            }
            
            // 地址范围未初始化时，返回空数组（不上报任何崩溃）
            kscrash_callCompletion(onCompletion, @[], nil);
            return;
        } else {
            NSLog(@"[MYKSCrashFilter] ✅ 地址范围初始化成功");
        }
    }
    
    for (id<KSCrashReport> report in reports) {
        // 获取报告的实际数据
        NSDictionary *reportDict = nil;
        
        // 尝试获取字典格式的报告内容
        if ([report isKindOfClass:[KSCrashReportDictionary class]]) {
            KSCrashReportDictionary *dictReport = (KSCrashReportDictionary *)report;
            reportDict = dictReport.value;
        } else {
            // 如果不是字典格式，无法进行地址筛选，跳过
            NSLog(@"[MYKSCrashFilter] 警告：报告不是字典格式，跳过");
            continue;
        }
        
        if (!reportDict) {
            NSLog(@"[MYKSCrashFilter] 警告：无法获取报告字典数据，跳过");
            continue;
        }
        
        // 使用地址筛选器判断是否应该上报该崩溃
        BOOL shouldReport = [addressFilter shouldReportCrash:reportDict];
        if (shouldReport) {
            NSLog(@"[MYKSCrashFilter] 找到 SDK 相关崩溃报告，已筛选");
            [filteredReports addObject:report];
        } else {
            NSLog(@"[MYKSCrashFilter] 非 SDK 相关崩溃报告，已过滤");
        }
    }

    NSLog(@"[MYKSCrashFilter] 筛选完成：原始报告 %lu 条，筛选后 %lu 条", 
          (unsigned long)reports.count, (unsigned long)filteredReports.count);
    
    // 使用kscrash_callCompletion安全地调用回调
    kscrash_callCompletion(onCompletion, filteredReports.copy, nil);
}

@end



